package com.untour.im.codec.protocol.packet.response;

import cn.hutool.core.util.RandomUtil;
import com.untour.im.codec.protocol.message.body.MessageBody;
import com.untour.im.codec.protocol.packet.client.HeartBeatServerResponsePacket;
import com.untour.im.codec.protocol.packet.client.LoginServerResponsePacket;
import com.untour.im.codec.protocol.packet.client.OfflineServerResponsePacket;
import com.untour.im.codec.protocol.packet.client.ResponsePacket;
import com.untour.im.codec.protocol.serialize.Serializer;
import com.untour.im.codec.protocol.serialize.SerializerAlgorithm;
import com.untour.im.codec.protocol.serialize.json.JSONSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 发送消息转化类
 */
@Slf4j
public class ResponsePacketCodec {
    public static final ResponsePacketCodec INSTANCE = new ResponsePacketCodec();

    private final Map<Byte, Serializer> serializerMap;

    private ResponsePacketCodec(){
        // 序列化协议ID 和 协议实现类 映射
        serializerMap = new HashMap<>();
        Serializer serializer = new JSONSerializer();
        serializerMap.put(serializer.getSerializerAlgorithm(), serializer);
    }
    private Serializer getSerializer(byte serializerType) {
        return serializerMap.get(serializerType);
    }

    /**
     * 发送心跳消息应答报文
     * @param ctx
     * @param messageId
     */
    public void sendHeartBeatResponseMessage(ChannelHandlerContext ctx, String messageId) {
        HeartBeatServerResponsePacket responsePacket = new HeartBeatServerResponsePacket(messageId,SerializerAlgorithm.JSON,"收到心跳，我等你！");
        ctx.writeAndFlush(responsePacket);
    }

    /**
     * 发送下线通知报文
     * @param channel
     */
    public void sendOfflineResponseMessage(Channel channel) {
        OfflineServerResponsePacket responsePacket = new OfflineServerResponsePacket(RandomUtil.randomNumbers(20),SerializerAlgorithm.JSON,"您已在其他设备上登录！");
        channel.writeAndFlush(responsePacket);
    }

    /**
     * 登录成功反馈报文
     * @param ctx
     * @param messageId
     */
    public void sendLoginResponseMessage(ChannelHandlerContext ctx, String messageId) {
        LoginServerResponsePacket responsePacket = new LoginServerResponsePacket(messageId,SerializerAlgorithm.JSON,"登录成功！");
        ctx.writeAndFlush(responsePacket);
    }


    public void encode(ByteBuf byteBuf, ResponsePacket<MessageBody> packet) {
        Serializer serializer = getSerializer(packet.getMessageType());

        // 1. 序列化 java 对象
        byte[] bytes = serializer.serialize(packet.getMessageBody());

        // 2. 实际编码过程
        byteBuf.writeByte(packet.getCommand());
        byteBuf.writeByte(packet.getMessageType());
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
    }
}
